<template>
  <div id="categoryManager">
    <!-- <h1>这是栏目管理</h1> -->
    <!-- 搜索框 -->
    <div class="categoryManager_top">
      <el-col :span="2">
        <el-button type="primary" @click="addCategory">添加</el-button>
      </el-col>
      <el-col :span="4">
        <el-input v-model="input" placeholder="请输入栏目名称" class="categoryName" />
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="search">查询</el-button>
      </el-col>
    </div>
    <!-- 表格 -->
    <div class="categoryManager_center">
      <el-table :data="categoryParent" stripe style="width: 100%">
        <el-table-column prop="id" label="编号" width="180" align="center" />
        <el-table-column prop="name" label="栏目名称" align="center" />
        <el-table-column prop="num" label="序号" align="center" />
        <el-table-column prop="cateP" label="父栏目" align="center" />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="delById(scope.$index,scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="changeCategory(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="categoryManager_footer">
      <el-pagination :current-page.sync="currentPage1" :page-size="pageSize" layout="total, prev, pager, next" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加模态框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="myform" :model="form" :rules="rules" label-width="100px" class="demo-form">
        <el-form-item label="栏目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item label="序号" prop="num">
          <el-input v-model="form.num" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="所属栏目" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择所属栏目">
            <el-option v-for="item in categoryTree" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('myform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'querystring'
export default {
  data() {
    return {
      input: '',
      category: [],
      categoryTree: [], // 所有父栏目相关内容
      currentPage1: 1,
      pageSize: 6,
      total: 0, // 数据总数

      dialogFormVisible: false,
      title: '添加栏目信息',
      form: {
        name: '',
        num: '',
        parentId: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入栏目名称', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入序号', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择所属栏目', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 将父栏目转成文字
    categoryParent() {
      var self = this
      // 1.获取所有栏目信息
      // console.log(this.category);
      // 2.获取所有栏目树信息，
      // console.log(this.categoryTree,'tree')
      // 3.进行匹配
      this.category.forEach((item) => {
        // item->每一个栏目对象 item.id
        for (var i = 0; i < self.categoryTree.length; i++) {
          // categoryTree[i]:每一个栏目树对象
          if (item.parentId == self.categoryTree[i].id) {//eslint-disable-line
            item.cateP = self.categoryTree[i].name
          }
        }
      })
      return this.category
    }
  },
  created() {
    this.findCategoryTree().then(res => {
      // console.log(res);
      // 栏目树查询完成
      this.categoryTree = res.data.data
      this.findCategory()
    })
  },
  methods: {
    // 给确定按钮绑定事件
    submitForm(formName) {
      var self = this
      // 1.获取表单数据+表单验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          // 2.发送请求
          self.$axios.post('/category/saveOrUpdate', qs.stringify(self.form)).then(res => {
            if (res.data.status == 200) {//eslint-disable-line
              // 保存成功

              self.$message({
                message: '恭喜你，保存成功',
                type: 'success'
              })
              self.findCategory()
            } else {
              // 保存失败
              self.$message.error('保存失败')
            }
            self.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 给添加按钮绑定事件
    addCategory() {
      this.dialogFormVisible = true
      this.title = '添加栏目信息'
      this.form = {
        name: '',
        num: '',
        parentId: ''
      }
    },
    // 给编辑按钮绑定事件
    changeCategory(row) {
      this.dialogFormVisible = true
      this.title = '修改栏目信息'
      this.form = {
        id: row.id,
        name: row.name,
        num: row.num,
        parentId: row.parentId
      }
    },
    // 给查询按钮绑定事件
    search() {
      // 1.获取用户输入内容
      // alert(this.input);
      if (this.input) {
        this.findCategory(this.input)
      } else {
        this.findCategory()
      }
    },

    // 分页按钮的函数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage1 = val
      this.findCategory()
    },
    // 封装函数 查询所有栏目信息
    findCategory(name) {
      if (name) {
        // 点击的是搜索
        var data = {
          page: this.currentPage1 - 1,
          pageSize: this.pageSize,
          name: name
        }
      } else {
        // 点击的是非搜索
        data = {
          page: this.currentPage1 - 1,
          pageSize: this.pageSize
        }
      }

      this.$axios.post('category/query', qs.stringify(data)).then(res => {
        // console.log(res);
        this.category = res.data.data.list
        this.total = res.data.data.total
      })
    },
    // 查询所有栏目信息
    // findAllCategory(){
    //     this.$axios.get('/category/findAll').then(res=>{
    //         this.allcategorys=res.data.data
    //     })
    // },
    // 给删除按钮绑定事件
    delById(index, row) {
      var id = row.id
      var self = this
      // console.log(index,row)   //index为第几行   row为当前行的数据
      this.$confirm('此操作将永久删除这条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.get('/category/deleteById', {
          params: { id }
        }).then((response) => {
          if (response.data.status == 200) {//eslint-disable-line
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            self.findCategory()
          } else {
            // 删除失败
            self.$message({
              showClose: true,
              message: '删除失败',
              type: 'error'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 封装查询父栏目的函数
    findCategoryTree() {
      return this.$axios.get('/category/findCategoryTree')
    }

  }

}
</script>
<style scoped>
    #categoryManager{
        padding: 20px;
    }
    .categoryName{
        padding-right: 20px;
    }

</style>
